package com.eci.context.context.swagger;

import com.eci.common.asset.constant.StringConstant;
import io.swagger.annotations.ApiOperation;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Collections;
import java.util.List;

@Configuration
@ConditionalOnProperty(value = "springfox.documentation.enabled", havingValue = "true", matchIfMissing = true)
public class SwaggerConfig {



    @Bean
    public Docket createRestApi() {

        Docket docket = new Docket(DocumentationType.OAS_30).apiInfo(apiInfo()).select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
        return docket;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("ECI-ERP平台----“平台配置系统”接口文档")
                .description("更多请咨询 www.ecinnovations.com")
                .version("1.0.0")
                .contact(new Contact("EC Innovations", "https://www.ecinnovations.com", "info@ecinnovations.com"))
                .build();
    }

    private List<SecurityScheme> securitySchemes() {

        ApiKey apikey = new ApiKey(StringConstant.Authority.AUTHORITY_HEADER, StringConstant.Authority.AUTHORITY_HEADER, ParameterType.HEADER.toString());

        return Collections.singletonList(apikey);
    }


    @SuppressWarnings("deprecation")
    private List<SecurityContext> securityContexts() {
        SecurityContext sc = SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("^(?!auth).*$")).build();

        return Collections.singletonList(sc);
    }

    List<SecurityReference> defaultAuth() {

        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");

        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;

        return Collections.singletonList(new SecurityReference(StringConstant.Authority.AUTHORITY_HEADER, authorizationScopes));
    }

}
